/**
 * @Author Helin
 * @date 2011-9-27
 * @mail hl_0074@sina.com
 */
(function() {
	var Context = '/';
	var scripts = document.getElementsByTagName("script");
	for ( var i = 0; i < scripts.length; i++) {
		if (/.*\/sj\.js$/g.test(scripts[i].getAttribute("src"))) {
			var jsPath = scripts[i].getAttribute("src").replace(/.*\/sj\.js$/g,
					'');
			if (jsPath.indexOf("/") == 0 || jsPath.indexOf("://") > 0) {
				Context = jsPath;
				break;
			}
			var arr1 = jsPath.split("/");
			var path = window.location.href;
			if (path.indexOf("?") != -1) {
				path = path.substring(0, path.indexOf("?"));
			}
			var arr2 = path.split("/");
			arr2.splice(arr2.length - 1, 1);
			for ( var i = 0; i < arr1.length; i++) {
				if (arr1[i] == "..") {
					arr2.splice(arr2.length - 1, 1);
				}
			}
			Context = arr2.join('/');
			break;
		}
	}
	window.SJ = {
			invoke:function(method, data, success, error, complete){
				SJ.ajax({
					url : Context + '/sj',
					data : {
						method : method,
						param : data
					},
					success : function(data) {
						var json={};
						try {
							 json = eval('(' + data + ')');
						} catch (e) {
							json.status=500;
						}
						if (json.status == 200) {
							if (success) {
								success.call(window, json.data);
							}
						} else if (json.status == 500) {
							if (error) {
								error.call(window, json.message);
							}
						}
					},
					error : function(xhr) {
						error.call(window, xhr.responseText);
					},
					complete : function() {
						if (complete) {
							complete.call(window);
						}
					}
				});
			},
			ajax:function(config){
				var http = SJ._http();

				var data = 'method=' + config.data.method;
				var param = SJ._makeData(config.data.param);
				if (param != '') {
					data = data + '&' + param;
				}

				http.open("POST", config.url, true);
				http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				http.send(data);
				http.onreadystatechange = function() {
					if (http.readyState == 4) {
						if (http.status == 200) {
							if (config.success) {
								config.success.call(window, http.responseText);
							} else if (config.error) {
								config.error.call(window, http);
							}
						}
						if (config.complete) {
							config.complete.call(window);
						}
					}
				};
			},
			_http:function(){
				return window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
			},
			_makeData:function(data){
				var s = [];
				if (data != null) {
					for ( var i in data) {
						s.push(i + '=' + data[i]);
					}
				}
				return s.join('&');
			}
	};
})();